package com.platform.comm.feign;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * 服务接口异常处理切面
 *
 * @author wxw Created on 2021/11/30
 **/
@Aspect
@Component
@Log4j2
public class InternalApiAspect {

    @Around(value = "(@annotation(com.platform.comm.feign.InternalAPI) && @annotation(internalApi)) || (@within(com.platform.comm.feign.InternalAPI) && @within(internalApi))")
    Object around4Method(ProceedingJoinPoint joinPoint, InternalAPI internalApi) throws Throwable {
        Object proceed;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            RequestAttributes attributes = RequestContextHolder.currentRequestAttributes();
            HttpServletResponse resp = ((ServletRequestAttributes) attributes).getResponse();
            assert resp != null;
            resp.setStatus(503);
            throw throwable;
        }
        return proceed;

    }

}
